<?php
namespace Home\Controller;
use Think\Controller;
class LoginController extends BaseController {

	private $m = NULL;
	private $m_class = NULL;
	private $navName = '会员登录';
	private $navHref;

	public function _initialize(){

		parent::_initialize();
		$this->WLang = ' language=\''.$this->defaultLang.'\' ';
		$this->addPrPv();
		$this->md = D('Admin/Member');
		$this->m_field = M('member_field');	
		$this->http_host=$_SERVER['HTTP_HOST'];
		
	}
	
	public function checkUser(){
		$result = $this->md->auth();
		!$result && $this->error('请登录后操作',U('Login/index'));
	}
	
    public function index(){
		$this->tplName = 'login';
		$this->assign("backurl",I("backurl")?I("backurl"):$_SERVER['HTTP_REFERER']);
		$this->display('Pages/'.$this->tplName);
    }
	
	//isLogin 顶部登录信息 <script src="{:U('Login/isLogin')}"><\/script>
	public function isLogin(){
		$Mxx='var toplink=\'\';';
		if(cookie( "AUTH_MEMBER_STRING")){
			$Mxx.='toplink+=\'<a class="a1">欢迎'.$this->username.'</a>\';';
			$Mxx.='toplink+=\'<a href="'.U("Member/index").'" title="会员中心" class="a1">会员中心</a>\';';
			$Mxx.='toplink+=\'<a href="'.U("Login/out").'" title="退出" class="a1">退出</a>\';';
		}else{
			$Mxx.='toplink+=\'<a href="'.U("Login/index").'" title="登录" class="a1">登录</a>\';';
			$Mxx.='toplink+=\'<a href="'.U("Login/reg").'" title="注册" class="a1">注册</a>\';';
		}
		echo $Mxx; echo 'document.write(toplink);'; exit;
	}
	
	//登录提交
	public function chkLogin(){
	
		$username = I('post.username');
		$password = I('post.userpwd');
		$valid = I('validCode');
		if(!$this->bascCheckValid($valid)){
			NewUrl(1,'验证码错误','-1');
		}
		//$Member = D('Admin/Member');
		 if(empty($username) || empty($password)){
			   $errorMsg = '请填写账号和密码！';
			   NewUrl(1,$errorMsg,'-1');
			   //$this->error($errorMsg);
		 }
		if ($username && $password) {
			$result = $this->md->login($username, $password);
			switch ($result){
				case 'noexist':
					$this->error('用户名或密码错误！');
					break;
				case 'nopass':
					$this->error('用户名或密码错误！');
					break;
				case 'islock':
					$this->error('用户是锁定状态，请联系管理员！');
					break;
				case 'ok':
					redirect(I('post.fhurl')?I('post.fhurl'):U('Member/index'));
					break;
			} //switch
		} else {
			$errorMsg = '请填写账号和密码！';
			NewUrl(1,$errorMsg,'-1');
			//$this->error($errorMsg);
		}
	
	}
	//注册
	public function reg(){
		$this->tplName = 'reg';
		$this->assign('backurl',I('backurl')?I('backurl'):$_SERVER['HTTP_REFERER']);
		
		$fieldList = $this->m_field->where('status=1')->order('list_order desc , id asc')->select();
		$this->assign('fieldList',$fieldList);
		$this->display('Pages/'.$this->tplName);
		
	}
	//注册提交
	public function regCheck(){
		$valid = I('validCode');
		$backurl=I('post.fhurl')?I('post.fhurl'):U('Member/index');
		if(!$this->bascCheckValid($valid)){
			NewUrl(1,'验证码错误','-1');
		}
		$data=$this->md->create(); //用此方法注意关键字段，如级别、锁定等
		if ($data['username']=='' || $data['password']=='' || $data['email']=='' ){
			NewUrl(1,'信息填写不全','-1');
		}
		$data['status']=0; //0锁定 1开放
		$data['AdminLevel']=1; //级别
		$data['addtime']=time(); //时间
		$data['login_ip'] = getIP();
		$result=$this->md->register($data);
		if($result==1){
			NewUrl(1,'注册成功！',$backurl);
		}elseif($result == false){
			NewUrl('1','注册失败！','-1');
		}else{
			NewUrl('1','该用户名已被占用！','-1');
		}
	}
	public function findPwd(){
		$this->tplName = 'findPwd';
		$this->display('Pages/'.$this->tplName);
	}
	public function findCheck(){
		header('Content-Type:text/html;charset=utf-8');
	
		$findArray['username'] = I('username')=='请输入用户名'?'':I('username');
		$findArray['email'] = I('email')=='请输入邮箱地址'?'':I('email');
		$valid = I('validCode')=='请输入验证码'?'':I('validCode');
		
		if(empty($findArray['username']) || empty($findArray['email'])){
			$this->error('请输入账号与邮箱');
		}
		
		if(!$this->bascCheckValid($valid)){
			NewUrl(1,'验证码错误','-1');
		}
		
		$webConfig = $this->webConfig;

		$member_id = $this->md->checkMemberEmail($findArray['username'], $findArray['email']);
		if ($member_id){
			$key = authcode($findArray['username']."\t".$findArray['email']."\t".(time()+86400),'ENCODE',C('AUTH_KEY'));
			//$passUpdateUrl = U('Login/updatePsw@'.$this->http_host,array('username'=>$findArray['username'],'validKey'=>$key));
			$passUpdateUrl = 'http://'.$this->http_host.U('Login/updatePsw',array('username'=>$findArray['username'],'validKey'=>$key));
			$mb_str = array("{{username}}", "{{sitename}}", "{{titleurl}}","{{linkurl}}");
			$mb_to_str   = array($findArray['username'], "<a href=\"".$this->http_host."\" title=\"".$webConfig['com_name']['val']."\" target=\"_blank\">".$webConfig['com_name']['val']."</a>","<a href=\"".$passUpdateUrl."\" title=\"设置新密码\" target=\"_blank\">设置新密码</a>", "<a href=\"".$passUpdateUrl."\" title=\"请点击此链接进入修改密码页面\" target=\"_blank\">".$passUpdateUrl."</a>");
			$find_content = str_replace($mb_str, $mb_to_str, wap_cv(M('admin_emailcontent')->where('id=1')->getField('content')));	///邮件模版
			
			$to = $findArray['email'];
			$name = $findArray['username'];
			$subject = $webConfig['site_name']['val']."提醒您：修改账户密码";
			$body = "<html>\n<body>\n".$find_content."</body>\n</html>\n";
			$result = think_send_mail($to , $name , $subject , $body);
			if($result){
					$this->success('密码修改邮件已经发送到你填写的邮箱中，请尽快收信修改密码',U('Login/findPwd'),5);
			}else{
					$this->error('密码修改邮件发送失败，请重新执行找回操作',U('Login/findPwd'));
			}
		} else {
			$this->error('你输入的邮箱有误');
		}
	
	}
	
	public function updatePsw(){
		header('Content-Type:text/html;charset=utf-8');
		$validKey = I('validKey');
		$username = I('username');
	
		if(!$validKey){
			$this->error('参数错误',U('Login/index'));
		}
		$this->assign('validKey',$validKey);
		
		$temp = authcode($validKey,'DECODE',C('AUTH_KEY'));
		$key = explode("\t",$temp);
		
		if($username != $key[0]){
			$this->error('参数错误,请重新取回密码',U('Login/index'));
		}
		if($key[2] < time() ){
			$this->error('已经超过时间限制，你必须在24小时内修改密码，请重新申请取回密码',U('Find/index'));
		}
		$this->tplName = 'Pages/findUpdate';
		$this->assign('pageTitle','修改密码_找回密码');
		$this->assign('username',$username);
		$this->display($this->tplName);	
	}
	
	
	public function savePsw(){	
		$temp = authcode(I('volidKey'),'DECODE',C('AUTH_KEY'));
		$key = explode("\t",$temp);
		$mima = I('mima');
		$password = I('password');
		if(empty($mima) || empty($password)){
			$this->error('请将表单填写完整');
		}
		if($this->md->updateFromGetPsw($key[0],$key[1],$password)){
			$this->success('修改密码成功，请重新登陆！',U('Login/index'));		
		}else{	
			$this->error('修改密码失败');
		}
	}
	
	//退出
	public function out(){
		//$Member = D('Admin/Member');
		$this->md->logout();
		redirect(U('Login/index'));
	}
	
	//验证码
	public function sendValid(){
	    $this->baseValid();exit;
	}
	
	//ajax验证码
	public function ajaxCheckValid(){
		//echo $this->bascCheckValid(I('validCode'));exit;
		$res = $this->bascCheckValid(I('validCode'));
		echo $res?1:0;exit;
	}
	
	//ajax会员名
	public function ajaxCheckUser(){
		$username = I('username');
		$user = M('member');
		$user_id = $user->where('username="'.$username.'"')->getField('id');
		echo $user_id?1:0;exit;
	}
	
	//ajax密码
	public function ajaxCheckPwd(){
		$username = I('username');
		$password = I('password');
		$user = M('member');
		$user_id = $user->where('username="'.$username.'" AND password="'.md5($password).'"')->getField('id');
		echo $user_id?1:0;exit;
	}




}